package com.tl.sun.ui.activity;

import android.os.Bundle;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.tl.sun.AppContext;
import com.tl.sun.OkHeader;
import com.tl.sun.R;
import com.tl.sun.manager.MDAccountMgr;
import com.tl.sun.manager.MDUserMgr;
import com.tl.sun.model.BaseModel;
import com.tl.sun.model.SessionEnetity;
import com.tl.sun.model.UserEnetity;
import com.tl.sun.utils.DeviceUuidFactory;
import com.tl.sun.utils.ToastUtil;
import com.tl.sun.utils.common.MD5Util;
import com.tl.sun.utils.common.RegularUtils;
import com.tl.sun.utils.core.EmptyUtils;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;

/**
 * 作者：HQY on 17/11/1 10:48
 * 邮箱：hqy_xz@126.com
 */

public class CreateAccountActiviy extends BaseActivity {

    @Bind(R.id.tv_generic_title)
    TextView mTvGenericTitle;
    @Bind(R.id.et_account_name)
    EditText mEtAccountName;
    @Bind(R.id.et_account_pass)
    EditText mEtAccountPass;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_create_account);
        ButterKnife.bind(this);
        mTvGenericTitle.setText("绑定/创建账号");
    }

    @OnClick({R.id.rl_generic_back, R.id.tv_account_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.rl_generic_back:
                onBackPressed();
                break;
            case R.id.tv_account_submit:
                String name = mEtAccountName.getText().toString();
                String password = mEtAccountPass.getText().toString();
                if (EmptyUtils.isNotEmpty(name)) {
                    if (EmptyUtils.isNotEmpty(password)) {
                        if (password.length() >= 6 && password.length() <= 20) {
                            if (RegularUtils.isUsername2(name)) {
                                bindAccount(name, password);
                            } else {
                                ToastUtil.showToast("用户名须是6~20位字母,数字");
                            }
                        } else {
                            ToastUtil.showToast(getResources().getString(R.string.et_length));
                        }
                    } else {
                        ToastUtil.showToast(getResources().getString(R.string.et_is_password_empty));
                    }
                } else {
                    ToastUtil.showToast(getResources().getString(R.string.et_is_name_empty));
                }
                break;
        }
    }


    private void bindAccount(final String username, final String password) {
        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHeadToken(this))
                .post(AppContext.getInstance().getBaseUrl() + "wx/bind_account")
                .params("username", username)
                .params("password", password)
                .tag(this)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel base = gson.fromJson(s, BaseModel.class);
                        if (base.getRet().equals("0")) {
                            login(username, password);
                        } else {
                            ToastUtil.showToast(base.getMsg());
                        }
                    }
                });

    }

    /**
     * 登录
     *
     * @param name
     * @param password
     */
    public void login(final String name, final String password) {

        HashMap<String, String> map = new HashMap<>();
        map.put("username", name);
        map.put("password", password);
        map.put("device_token", MDAccountMgr.getInstance().getDeviceToken());
        map.put("client_id", MD5Util.md5(new DeviceUuidFactory(AppContext.getInstance()).getDeviceUuid().toString()));
        JSONObject jsonObject = new JSONObject(map);

        OkGo.getInstance().addCommonHeaders(OkHeader.getCommonHead(this)).post(AppContext.getInstance().getBaseUrl() + "account/login_v2")
                .tag(this)
                .upJson(jsonObject.toString())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(String s, Call call, Response response) {
                        Gson gson = new Gson();
                        BaseModel baseModels = gson.fromJson(s, BaseModel.class);
                        if (baseModels.getRet().equals("0")) {
                            Type userType = new TypeToken<BaseModel<SessionEnetity>>() {
                            }.getType();
                            BaseModel<SessionEnetity> baseModel;
                            try {
                                baseModel = gson.fromJson(s, userType);
                            } catch (JsonSyntaxException e) {
                                baseModel = gson.fromJson(s, BaseModel.class);
                            }
                            MDAccountMgr.getInstance().setLoginType("0");
                            SessionEnetity sessionInfo = baseModel.getData();
                            MDAccountMgr.getInstance().setSessionId(sessionInfo.getSession());
                            UserEnetity user = sessionInfo.getUserInfo();
                            MDUserMgr.getInstance().setAvatar(user.getAvatar());
                            MDUserMgr.getInstance().setAwardFlag(user.getAward_flag());
                            MDUserMgr.getInstance().setId(user.getId());
                            MDUserMgr.getInstance().setUsername(user.getUsername());
                            MDUserMgr.getInstance().setShowName(user.getShowNmae());
                            MDUserMgr.getInstance().setNickname(user.getNick_name());
                            MDUserMgr.getInstance().setChange(user.getChange());
                            MDUserMgr.getInstance().setEmail(user.getEmail());
                            MDUserMgr.getInstance().setPhone(user.getPhone());
                            MDUserMgr.getInstance().setMoney(Double.valueOf(user.getMoney()));
                            MDUserMgr.getInstance().setLastTime(user.getLast_time());
                            MDUserMgr.getInstance().setLastTimeType(user.getLast_time_type());
                            MDUserMgr.getInstance().setStatus(user.getStatus());
                            MDUserMgr.getInstance().setToken(user.getToken());
                            MDUserMgr.getInstance().setTime(user.getnVipTime());
                            MDUserMgr.getInstance().setsTime(user.getsVipTime());
                            MDUserMgr.getInstance().setCoupoum(user.getCoupoum());
                            MDUserMgr.getInstance().setLogin(true);//保存到类
                            MDUserMgr.getInstance().setOrigin(user.getOrigin());
                            MDUserMgr.getInstance().setThreeDayExpire(user.getThreeDayExpire());
                            MDAccountMgr.getInstance().setLogin(true);//保存到内存
                            MDAccountMgr.getInstance().setLoginName(user.getShowNmae());
                            MDAccountMgr.getInstance().setLoginPwd(password);
                            MDAccountMgr.getInstance().setPassowrd(true);
                            MDAccountMgr.getInstance().writeToCache(CreateAccountActiviy.this);
                            finish();
                        }
                    }

                    @Override
                    public void onError(Call call, Response response, Exception e) {
                        ToastUtil.showToast("网络请求失败");

                    }

                });
    }

}
